package sequence

import (
	"database/sql"
	"fmt"
	"shortURL/pool"
)

func init() {
	seq := &SequenceDB{}
	seq.Open()
	RegisterSequence("db", seq)
}

type SequenceDB struct {
}

func (dbSeq *SequenceDB) Open() (err error) {
	return nil
}

func (dbSeq *SequenceDB) Close() {

}

func (dbSeq *SequenceDB) NextSequence() (sequence uint64, err error) {
	conn, err := pool.GetDbConn("default")
	defer pool.PutDbConn("default", conn)
	if err != nil {
		return 0, fmt.Errorf("pool conn err:%w", err)
	}

	var stmt *sql.Stmt
	stmt, err = conn.DB().Prepare(`REPLACE INTO sequence(stub) VALUES ("sequence")`)
	if err != nil {
		return 0, fmt.Errorf("sql prepare err:%w", err)
	}
	defer stmt.Close()

	var res sql.Result
	res, err = stmt.Exec()
	if err != nil {
		return 0, fmt.Errorf("sql exec err:%w", err)
	}

	// 兼容LastInsertId方法的返回值
	var lastID int64
	lastID, err = res.LastInsertId()
	if err != nil {
		return 0, fmt.Errorf("sql get LastInsertId err:%w", err)
	} else {
		sequence = uint64(lastID)
		// mysql sequence will start at 1, we actually want it to be
		// started at 0. :)
		sequence -= 1
		return sequence, nil
	}
}
